package cn.rcth.controller;
 
import net.sf.json.JSONObject;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
 
/**
 * @Author:
 * @Date: 2018/3/28 16:05
 * 调用微信公众平台主动发消息接口
 */
public class Wechat {
 
    public static void main(String[] args) throws IOException {

 
        //发送消息
        JSONObject text = new JSONObject();
        text.element("content", "内容");
        JSONObject json = new JSONObject();
        json.element("touser", "oNLtTw6H2Rx5Qg-SWaEjsbKfPkGY");
        json.element("text", text);
        json.element("msgtype", "text");
      //  customSend(json, token);
 
        //发送图片
        JSONObject media_id = new JSONObject();
        String filePath = "E:\\SougouImages\\SogouWP\\Net\\WallPaper\\405376.jpg";
        media_id.element("media_id", upload(filePath, "token", "image"));
        JSONObject json1 = new JSONObject();
        json1.element("touser", "oNLtTw6H2Rx5Qg-SWaEjsbKfPkGY");
        json1.element("image", media_id);
        json1.element("msgtype", "image");
       // customSend(json1, token);
    }
 
    /**
     * 获取code
     */
    //https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=redirect_uri&response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect
 
    /**
     * 获取code后，根据code获取openid
     */
    //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=secret&code=$code&grant_type=authorization_code
 
 
    /**
     * 发送图片
     * @param filePath
     * @param accessToken
     * @param type
     * @return
     * @throws IOException
     */
    public static String upload(String filePath, String accessToken, String type) throws IOException {
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            throw new IOException("文件不存在");
        }
        //String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+ accessToken +"&type="+ type;
        URL urlobj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlobj.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
 
        //设置头信息
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
 
        //设置边界
        String BOUNFARY = "----------" + System.currentTimeMillis();
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNFARY);
 
        StringBuilder sb = new StringBuilder();
        sb.append("--");
        sb.append(BOUNFARY);
        sb.append("\r\n");
        sb.append("Content-Disposition:from-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
        sb.append("Content-Type:application/actet-stream\r\n\r\n");
 
        byte[] head = sb.toString().getBytes("utf-8");
        //获得输出流
        OutputStream out = new DataOutputStream(conn.getOutputStream());
        //输出表头
        out.write(head);
 
        //文件正文部分
        //把文件以流的方式 推入到url
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();
        //结尾部分
        byte[] foot = ("\r\n--" + BOUNFARY + "--\r\n").getBytes("utf-8");
        out.write(foot);
        out.flush();
        out.close();
 
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        String result = null;
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        if (result == null) {
            result = buffer.toString();
        }
        if (result != null) {
            reader.close();
        }
        JSONObject jsonObject = JSONObject.fromObject(result);
        System.out.println(jsonObject);
        String typeName = "media_id";
        if (!"image".equals(type) && !"voice".equals(type) && !"video".equals(type)) {
            typeName = type + "_media_id";
        }
        String mediaid = jsonObject.getString(typeName);
        return mediaid;
    }



 

}
